package com.authine.cloudpivot.web.api.helper.oraganization;

import com.authine.cloudpivot.engine.api.exceptions.ServiceException;
import com.authine.cloudpivot.engine.api.facade.OrganizationFacade;
import com.authine.cloudpivot.engine.api.model.organization.*;
import com.authine.cloudpivot.engine.api.model.system.RelatedCorpSettingModel;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.enums.status.UserStatus;
import com.authine.cloudpivot.engine.enums.type.OrgType;
import com.authine.cloudpivot.engine.enums.type.UnitType;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.util.DateUtils;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.organization.UserManagerVO;
import com.authine.cloudpivot.web.api.view.organization.UserVO;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.*;
import java.util.stream.Collectors;

//import com.authine.cloudpivot.engine.enums.type.UserSourceType;
//import com.authine.cloudpivot.engine.enums.type.UserSourceType;

@Slf4j
public class UserHelper {
    private DubboConfigService dubboConfigService;

    private String mainCorpId;

    private final static String USER_MODIFY_KEY = "user_modify:";

    public UserHelper(DubboConfigService dubboConfigService, String corpId) {
        this.dubboConfigService = dubboConfigService;
        this.mainCorpId = corpId;
    }

    private <T> ResponseResult<T> getErrResponseResult(T t, Long errCode, String errMsg) {
        return ResponseResult.<T>builder().data(t).errcode(errCode).errmsg(errMsg).build();
    }

    private <T> ResponseResult<T> getOkResponseResult(T t, String errMsg) {
        return getErrResponseResult(t, ErrCode.OK.getErrCode(), errMsg);
    }

    //创建用户
    public ResponseResult<UserVO> create(UserVO userVO) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        if (userVO == null) {
            throw new ServiceException(ErrCode.SYS_PARAMETER_EMPTY.getErrCode(), ErrCode.SYS_PARAMETER_EMPTY.getErrMsg(), "");
        }
        String name = userVO.getName();
        String corpId = userVO.getCorpId();
        if (StringUtils.isEmpty(corpId)) {
            DepartmentModel departmentModel = organizationFacade.getDepartment(userVO.getDepartmentId());
            if (departmentModel != null && StringUtils.isNotEmpty(departmentModel.getCorpId())) {
                corpId = departmentModel.getCorpId();
            }
        }
        if (StringUtils.isEmpty(name)) {
            return getErrResponseResult(null, ErrCode.ORG_USER_NAME_EMPTY.getErrCode(), ErrCode.ORG_USER_NAME_EMPTY.getErrMsg());
        }
        String username = userVO.getUsername();
        if (StringUtils.isEmpty(username)) {
            return getErrResponseResult(null, ErrCode.ORG_USER_ACCOUNT_EMPTY.getErrCode(), ErrCode.ORG_USER_ACCOUNT_EMPTY.getErrMsg());
        }

        if (StringUtils.isEmpty(corpId)) {
            corpId = mainCorpId;
        }

        UserModel user = organizationFacade.getUserByUserNameAndCorpId(username, corpId);

        if (user != null && Objects.equals(user.getStatus(), UserStatus.ENABLE)) {
            return getErrResponseResult(null, ErrCode.ORG_USER_ACCOUNT_UNIQUE.getErrCode(), ErrCode.ORG_USER_ACCOUNT_UNIQUE.getErrMsg());
        }
        String departmentId = userVO.getDepartmentId();
        if (StringUtils.isEmpty(departmentId)) {
            return getErrResponseResult(null, ErrCode.ORG_USER_DEPT_EMPTY.getErrCode(), ErrCode.ORG_USER_DEPT_EMPTY.getErrMsg());
        }

        String mobile = userVO.getMobile();
        if (StringUtils.isEmpty(mobile)) {
            return getErrResponseResult(null, ErrCode.ORG_USER_MOBILE_NONEXIT.getErrCode(), ErrCode.ORG_USER_MOBILE_NONEXIT.getErrMsg());
        }

        if (Boolean.FALSE.equals(userVO.getIsImport())) {
            RelatedCorpSettingModel relatedCorpSettingModel = dubboConfigService.getSystemManagementFacade().getRelatedCorpSettingModelByCorpId(corpId);

            if (OrgType.MAIN != relatedCorpSettingModel.getOrgType()) {
                List<UserModel> userByMobile = organizationFacade.getUsersByMobile(mobile);
                if (CollectionUtils.isNotEmpty(userByMobile)) {
                    userByMobile = userByMobile.stream().filter(Objects::nonNull).filter(item -> UserStatus.ENABLE == item.getStatus()).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(userByMobile)) {
                        return getErrResponseResult(null, ErrCode.ORG_USER_MOBILE_UNIQUE.getErrCode(), "该(" + mobile + ")用户已存在,不允许新增");
                    }
                }
            } else {
                UserModel userByMobile = organizationFacade.getUserByMobileAndCorpId(mobile, corpId);
                if (userByMobile != null && UserStatus.ENABLE == userByMobile.getStatus()) {
                    return getErrResponseResult(null, ErrCode.ORG_USER_MOBILE_UNIQUE.getErrCode(), "该(" + mobile + ")用户已存在,不允许新增");
                }
            }
        }

        //导入的人员已存在userId重复问题
        UserModel userUserIdModel = organizationFacade.getUserByUserIdAndCorpId(userVO.getUsername(), corpId);
        if (userUserIdModel != null) {
            return getErrResponseResult(null, ErrCode.ORG_USER_MOBILE_UNIQUE.getErrCode(), "该(" + userVO.getUsername() + ")用户账号已存在,不允许新增");
        }

        UserModel userByMobile = organizationFacade.getUserByMobileAndCorpId(mobile, corpId);
        if (userByMobile != null && Objects.equals(userByMobile.getStatus(), UserStatus.ENABLE)) {
            return getErrResponseResult(null, ErrCode.ORG_USER_MOBILE_UNIQUE.getErrCode(), ErrCode.ORG_USER_MOBILE_UNIQUE.getErrMsg());
        }
        String employeeNo = userVO.getEmployeeNo();
        if (StringUtils.isNotEmpty(employeeNo)) {
            UserModel userModel = organizationFacade.searchUserByEmployeeNoAndCorpId(employeeNo, corpId);
            if (userModel != null && Objects.equals(userModel.getStatus(), UserStatus.ENABLE)) {
                return getErrResponseResult(userVO, ErrCode.ORG_USER_EMPLOYEENO_UNIQUE.getErrCode(), ErrCode.ORG_USER_EMPLOYEENO_UNIQUE.getErrMsg());
            }
        }
        String id = null;
        //根据用户手机号码在数据库中已经存在并且用户状态为禁用状态做返聘逻辑
        if (userByMobile != null && Objects.equals(userByMobile.getStatus(), UserStatus.DISABLE)) {
            id = reEmployment(userByMobile, userVO);
        }
        //新增用户
        if (userByMobile == null) {
            id = addUser(userVO);
        }

        List<String> deptIds = userVO.getDeptIds();
        List<String> roleIds = userVO.getRoleIds();
        deptIds.add(departmentId);
        for (String deptId : deptIds) {
            addDeptUser(deptId, id);
        }
        if (CollectionUtils.isNotEmpty(roleIds)) {
            for (String roleId : roleIds) {
                addRoleUser(roleId, id);
            }
        }
        updateUserManagerConfig(id, userVO.getUserManagerConfigList());
        userVO.setId(id);
        return getOkResponseResult(userVO, "创建用户/返聘成功");
    }

    //创建用户
    private String addUser(UserVO userVO) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        UserModel userModel = new UserModel();
        userModel.setEmployeeNo(userVO.getEmployeeNo());
        userModel.setEmail(userVO.getEmail());
        userModel.setMobile(userVO.getMobile());
        userModel.setDepartmentId(userVO.getDepartmentId());
        userModel.setCreatedTime(new Date());
        userModel.setName(userVO.getName());
        userModel.setUserId(userVO.getUsername());
        userModel.setStatus(UserStatus.ENABLE);
        userModel.setUsername(userVO.getUsername());
        userModel.setPassword(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123456"));
        userModel.setEntryDate(DateUtils.formateDateTime(userVO.getEntryTime()));
        userModel.setUnitType(UnitType.USER);
//        userModel.setUserSourceType(UserSourceType.YUN_SHU_USER);
        userModel.setOfficePhone(userVO.getOfficePhone());
        userModel.setImgUrl(userVO.getImgUrl());
        userModel.setImgUrlId(userVO.getImgUrlId());
        userModel.setGender(userVO.getGender());
        String corpId = userVO.getCorpId();
        if (StringUtils.isEmpty(corpId)) {
            DepartmentModel departmentModel = organizationFacade.getDepartment(userVO.getDepartmentId());
            if (departmentModel != null && StringUtils.isNotEmpty(departmentModel.getCorpId())) {
                corpId = departmentModel.getCorpId();
            }
        }
        userModel.setCorpId(corpId);
        UserModel user = organizationFacade.addUser(userModel);
        //新增拓展信息
        List<UserUnionExtAttrModel> userUnions = userVO.getUserUnion();
        if (CollectionUtils.isNotEmpty(userUnions)) {
            userUnions.forEach(model -> {
                model.setUserId(user.getId());
                dubboConfigService.getUserExtendFacade().saveUserUnion(model);
            });
        }
        return user.getId();
    }

    //创建部门用户中间关系
    private void addDeptUser(String deptId, String userId) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        if (StringUtils.isEmpty(deptId) || StringUtils.isEmpty(userId)) {
            return;
        }
        DepartmentUserModel deptUser = organizationFacade.getDepartmentUserByDeptIdAndUserId(deptId, userId);
        if (deptUser == null) {
            deptUser = new DepartmentUserModel();
        }
        deptUser.setUserId(userId);
        deptUser.setDeptId(deptId);
        organizationFacade.addDepartmentUser(deptUser);

    }

    //创建角色用户中间关系
    private void addRoleUser(String roleId, String userId) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        if (StringUtils.isEmpty(roleId) || StringUtils.isEmpty(userId)) {
            return;
        }
        RoleModel role = organizationFacade.getRole(roleId);
        String name = role.getName();
        boolean equals = Objects.equals(name, "主管");
        if (equals) {
            return;
        }
        RoleUserModel roleUserModel = organizationFacade.getRoleUserByRoleIdAndUserId(roleId, userId);
        if (roleUserModel == null) {
            roleUserModel = new RoleUserModel();
        }
        roleUserModel.setUserId(userId);
        roleUserModel.setRoleId(roleId);
        roleUserModel.setUnitType(UnitType.USER);
        organizationFacade.addRoleUser(roleUserModel);
    }

    //返聘用户
    private String reEmployment(UserModel userModel, UserVO userVO) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        userModel.setEmployeeNo(userVO.getEmployeeNo());
        userModel.setEmail(userVO.getEmail());
        userModel.setMobile(userVO.getMobile());
        userModel.setDepartmentId(userVO.getDepartmentId());
        userModel.setName(userVO.getName());
        userModel.setUserId(userVO.getUsername());
        userModel.setStatus(UserStatus.ENABLE);
        userModel.setUsername(userVO.getUsername());
        userModel.setPassword(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123456"));
        userModel.setUnitType(UnitType.USER);
        userModel.setOfficePhone(userVO.getOfficePhone());
        userModel.setImgUrl(userVO.getImgUrl());
        userModel.setImgUrlId(userVO.getImgUrlId());
        userModel.setGender(userVO.getGender());
        userModel.setDeleted(false);
        UserModel user = organizationFacade.updateUser(userModel);
        return user.getId();
    }

    //编辑用户
    public ResponseResult<UserVO> modified(UserVO userVO) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        if (userVO == null) {
            throw new ServiceException(ErrCode.SYS_PARAMETER_EMPTY.getErrCode(), ErrCode.SYS_PARAMETER_EMPTY.getErrMsg(), "");
        }
        String id = userVO.getId();
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ErrCode.ORG_USER_ID_EMPTY.getErrCode(), ErrCode.ORG_USER_ID_EMPTY.getErrMsg(), "");
        }
        UserModel user = organizationFacade.getUser(id);
        if (user != null && Objects.equals(user.getStatus(), UserStatus.DISABLE)) {
            return getErrResponseResult(userVO, ErrCode.ORG_USER_DISABLE.getErrCode(), ErrCode.ORG_USER_DISABLE.getErrMsg());
        }
        if (user == null) {
            return getErrResponseResult(userVO, -1L, "未选定用户");
        }
        String employeeNo = userVO.getEmployeeNo();
        if (StringUtils.isNotEmpty(employeeNo)) {
            UserModel userModel = organizationFacade.searchUserByEmployeeNoAndCorpId(employeeNo, user.getCorpId());
            if (userModel != null && Objects.equals(userModel.getStatus(), UserStatus.ENABLE) && (!Objects.equals(userModel.getId(), userVO.getId()))) {
                return getErrResponseResult(userVO, ErrCode.ORG_USER_EMPLOYEENO_UNIQUE.getErrCode(), ErrCode.ORG_USER_EMPLOYEENO_UNIQUE.getErrMsg());
            }
        }
        //①属性修改
        modifyUser(user, userVO);
        //②部门用户中间中间关系修改
        List<String> deptIds = userVO.getDeptIds();
        deptIds.add(userVO.getDepartmentId());
        List<DepartmentUserModel> deptUsers = organizationFacade.getDepartmentUsersByUserId(user.getId());
        if (CollectionUtils.isEmpty(deptUsers)) {
            return getErrResponseResult(userVO, ErrCode.ORG_USER_DEPT_EMPTY.getErrCode(), ErrCode.ORG_USER_DEPT_EMPTY.getErrMsg());
        }
        //先考虑新增的
        //departIds 为初始部门用户中间关系部门id    deptIds 为编辑后的
        List<String> departIds = deptUsers.stream().map(DepartmentUserModel::getDeptId).collect(Collectors.toList());
        List<String> ids = new ArrayList<>(deptIds);
        deptIds.removeAll(departIds);
        boolean empty2 = CollectionUtils.isEmpty(deptIds);
        if (!empty2) {
            for (String deptId : deptIds) {
                addDeptUser(deptId, user.getId());
            }
        }
        //考虑多余的
        departIds.removeAll(ids);
        boolean empty3 = CollectionUtils.isEmpty(departIds);
        if (!empty3) {
            for (String departId : departIds) {
                deleteDeptUser(departId, user.getId());
            }
        }

        //③角色用户中间关系修改
        List<RoleUserModel> roleUsers = organizationFacade.getRoleUsersByUserId(user.getId());
        List<String> roleIds = userVO.getRoleIds();
        boolean empty = CollectionUtils.isEmpty(roleUsers);
        boolean empty1 = CollectionUtils.isEmpty(roleIds);
        //本身为空角色 不管初始状态，否则先移除用户身上中间关系 然后再添加新增的角色用户关系
        if (!empty) {
            deleteRoleUsers(roleUsers);
        }
        if (!empty1) {
            for (String roleId : roleIds) {
                addRoleUser(roleId, user.getId());
            }
        }

        //查询是否有其他主管身份
        List<DepartmentUserModel> deptUserList = organizationFacade.getDepartmentUsersByUserId(userVO.getId());
        List<String> managerIds = Lists.newArrayList();
        for (DepartmentUserModel departmentUserModel : deptUserList) {
            String deptId = departmentUserModel.getDeptId();
            DepartmentModel department = organizationFacade.getDepartment(deptId);
            String managerId = department.getManagerId();
            if (StringUtils.isNotEmpty(managerId)) {
                managerIds.add(managerId);
            }
        }
        if ((CollectionUtils.isNotEmpty(managerIds) && (!managerIds.contains(user.getUserId()))) || CollectionUtils.isEmpty(managerIds)) {
            List<RoleModel> roleModels = organizationFacade.searchRoleByRoleName("部门主管");
            roleModels = roleModels.stream().filter(Objects::nonNull).filter(item -> StringUtils.isNotEmpty(user.getCorpId()) && user.getCorpId().equals(item.getCorpId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(roleModels)) {
                String id1 = roleModels.get(0).getId();
                RoleUserModel roleUserByRoleIdAndUserId = organizationFacade.getRoleUserByRoleIdAndUserId(id1, user.getId());
                if (roleUserByRoleIdAndUserId != null) {
                    organizationFacade.removeRoleUser(roleUserByRoleIdAndUserId);
                }
            }
        }

        // 处理直属主管关系
        updateUserManagerConfig(id, userVO.getUserManagerConfigList());

        if (StringUtils.isNotEmpty(user.getCorpId()) && StringUtils.isNotEmpty(user.getSourceId()) && !user.getSourceId().startsWith("CP")) {
            if (!organizationFacade.pullUserToDingDing(ImmutableList.of(user.getId()))) {
                throw new ServiceException(ErrCode.ORG_USER_PULL_NOTSUCCESS.getErrCode(), ErrCode.ORG_USER_PULL_NOTSUCCESS.getErrMsg());
            }
        }
        return getOkResponseResult(userVO, "编辑用户成功");
    }

    /**
     * 更新用户的直属主管配置
     *
     * @param userId
     * @param managerConfigList
     */
    private void updateUserManagerConfig(String userId, List<UserVO.UserManagerConfig> managerConfigList) {
        if (CollectionUtils.isEmpty(managerConfigList)) {
            return;
        }
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        List<OrgDirectManagerModel> list = new ArrayList<>();
        managerConfigList.forEach(item -> {
            if (StringUtils.isBlank(item.getManagerId())) {
                // 如果无直属主管配置，跳过
                return;
            }
            List<DepartmentUserModel> managerDeptList = organizationFacade.getDepartmentUsersByUserId(item.getManagerId());
            if (CollectionUtils.isEmpty(managerDeptList)) {
                log.error("无法查询到直属主管{}的部门信息", item.getManagerId());
                throw new ServiceException(ErrCode.ORG_USER_DEPT_EMPTY);
            }
            if (managerDeptList.stream().noneMatch(managerDept -> item.getDeptId().equals(managerDept.getDeptId()))) {
                log.error("直属主管({})不属于该部门({})", item.getManagerId(), item.getDeptId());
                throw new ServiceException(ErrCode.ORG_USER_MANAGER_DEPT_NOT_MATCH);
            }
            OrgDirectManagerModel model = new OrgDirectManagerModel();
            model.setUserId(userId);
            model.setDeptId(item.getDeptId());
            model.setManagerId(item.getManagerId());
            list.add(model);
        });
        organizationFacade.updateUserManagerConfig(userId, list);
    }

    //删除部门用户属性
    private void deleteDeptUser(String deptId, String userId) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        UserModel user = organizationFacade.getUser(userId);
        String id = user.getUserId();
        DepartmentModel department = organizationFacade.getDepartment(deptId);
        String managerId = department.getManagerId();
        if (StringUtils.isNotEmpty(managerId) && Objects.equals(managerId, id)) {
            department.setManagerId("");
            organizationFacade.updateDepartment(department);
        }
        DepartmentUserModel deptIdAndUserId = organizationFacade.getDepartmentUserByDeptIdAndUserId(deptId, userId);
        if (deptIdAndUserId != null) {
            organizationFacade.removeDeptUser(deptIdAndUserId);
        }
    }

    //编辑用户属性
    private void modifyUser(UserModel userModel, UserVO userVO) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        userModel.setImgUrl(userVO.getImgUrl());
        userModel.setImgUrlId(userVO.getImgUrlId());
        userModel.setGender(userVO.getGender());
        userModel.setName(userVO.getName());
        userModel.setOfficePhone(userVO.getOfficePhone());
        userModel.setEmail(userVO.getEmail());
        userModel.setEntryDate(DateUtils.formateDateTime(userVO.getEntryTime()));
        userModel.setDepartmentId(userVO.getDepartmentId());
        userModel.setEmployeeNo(userVO.getEmployeeNo());

        //编辑拓展字段
        List<UserUnionExtAttrModel> userUnion = userVO.getUserUnion();
        if (CollectionUtils.isNotEmpty(userUnion)) {
            userUnion.forEach(model -> {
                UserUnionExtAttrModel unionExtAttrModel = dubboConfigService.getUserExtendFacade().getUnionExtAttrsByUserIdAndExtendAttrId(model.getUserId(), model.getExtendAttrId());
                if (!Objects.isNull(unionExtAttrModel)) {
                    model.setId(unionExtAttrModel.getId());
                }
                dubboConfigService.getUserExtendFacade().saveUserUnion(model);
            });
        }

        organizationFacade.updateUser(userModel);
        //存儲分佈式鎖，在前端刷新頁面調用users接口時會回滾數據，需要在這裡做處理存儲鎖
//        RedisLockService.saveLock(getUserModifyKey(userModel.getId()),20);
    }


    public static String getUserModifyKey(String userId) {
        return USER_MODIFY_KEY + userId;
    }

    //删除角色用户
    private void deleteRoleUsers(List<RoleUserModel> roleUsers) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        if (CollectionUtils.isEmpty(roleUsers)) {
            return;
        }
        for (RoleUserModel roleUserModel : roleUsers) {
            organizationFacade.removeRoleUser(roleUserModel);
        }
    }


    //删除用户
    public ResponseResult<String> delete(String id) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ErrCode.SYS_PARAMETER_EMPTY.getErrCode(), ErrCode.SYS_PARAMETER_EMPTY.getErrMsg(), "");
        }
        UserModel user = organizationFacade.getUser(id);
        if (user != null && Objects.equals(user.getStatus(), UserStatus.DISABLE)) {
            return getErrResponseResult(id, ErrCode.ORG_USER_DISABLE.getErrCode(), ErrCode.ORG_USER_DISABLE.getErrMsg());
        }
        if (user == null) {
            return getErrResponseResult(id, ErrCode.ORG_USER_NONEXISTENT.getErrCode(), ErrCode.ORG_USER_NONEXISTENT.getErrMsg());
        }

        if (!organizationFacade.deleteDingUser(id)) {
            throw new ServiceException(ErrCode.ORG_USER_PULL_NOTSUCCESS.getErrCode(), "删除钉钉用户失败！");
        }

        //移除部门用户中间关系
        List<DepartmentUserModel> deptUsers = organizationFacade.getDepartmentUsersByUserId(id);
        if (CollectionUtils.isEmpty(deptUsers)) {
            return getErrResponseResult(id, ErrCode.ORG_USER_DEPT_EMPTY.getErrCode(), ErrCode.ORG_USER_DEPT_EMPTY.getErrMsg());
        }
        //departIds 用户的部门用户中间关系
        List<String> departIds = deptUsers.stream().map(DepartmentUserModel::getDeptId).collect(Collectors.toList());
        for (String departId : departIds) {
            DepartmentModel department = organizationFacade.getDepartment(departId);
            String managerId = department.getManagerId();
            if (Objects.equals(user.getUserId(), managerId)) {
                department.setManagerId("");
                organizationFacade.updateDepartment(department);
            }
            deleteDeptUser(departId, id);
        }

        //移除角色用户中间关系
        List<RoleUserModel> roleUsers = organizationFacade.getRoleUsersByUserId(id);
        boolean notEmpty = CollectionUtils.isNotEmpty(roleUsers);
        if (notEmpty) {
            deleteRoleUsers(roleUsers);
        }

        // 移除用户的直属主管相关配置
        organizationFacade.deleteUserManagerConfig(id);

        //修改用户的属性并给禁用标识
        deleteUser(user);

        return getOkResponseResult(id, "删除用户成功");
    }

    private void deleteUser(UserModel userModel) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        userModel.setDepartmentId("");
        userModel.setStatus(UserStatus.DISABLE);
        userModel.setManagerId("");
        userModel.setModifiedTime(new Date());
        userModel.setAdmin(false);
        userModel.setLeader(false);
        //将邮箱，办公电话，编号等清楚
        userModel.setEmail(null);
        userModel.setOfficePhone(null);
        userModel.setEmployeeNo(null);
        userModel.setDeleted(Boolean.TRUE);
        userModel.setSourceId("");
        organizationFacade.updateUser(userModel);
    }

    public ResponseResult<String> modifyUserPassword(Map<String, String> params) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        String username = params.get("username");
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        String corpId = params.get("corpId");

        if (StringUtils.isEmpty(corpId)) {
            corpId = mainCorpId;
        }

        if (StringUtils.isEmpty(username)) {
            log.error("输入的账号参数为空");
            return getErrResponseResult(null, ErrCode.SYSTEM_SETTING_VALUE_EMPTY.getErrCode(), ErrCode.SYSTEM_SETTING_VALUE_EMPTY.getErrMsg());

        }

        UserModel entity = organizationFacade.getUserByUserNameAndCorpId(username, corpId);
        if (null == entity) {
            return getErrResponseResult(null, ErrCode.ORG_USER_ACCOUNT_INVALID.getErrCode(), ErrCode.ORG_USER_ACCOUNT_INVALID.getErrMsg());
        }
        String name = entity.getName();
        if (Objects.equals(name, "admin")) {
            return getErrResponseResult(null, -1L, "超管的密码不允许在前台修改");
        }
        String password = entity.getPassword();
        if (StringUtils.isEmpty(oldPassword)) {
            log.error("输入的密码为空");
            return getErrResponseResult(null, ErrCode.SYSTEM_SETTING_VALUE_EMPTY.getErrCode(), ErrCode.SYSTEM_SETTING_VALUE_EMPTY.getErrMsg());
        }
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        boolean matches = encoder.matches(oldPassword, password);
        UserVO userVO = new UserVO();
        userVO.setUsername(entity.getUsername());
        if (matches) {

            if (StringUtils.isEmpty(newPassword)) {
                log.info("输入的新密码为空");
                return null;
            }
            boolean matches1 = encoder.matches(newPassword, password);
            if (matches1) {
                return getErrResponseResult(username, ErrCode.ORG_USER_PASSWORD_CONSISTENT.getErrCode(), ErrCode.ORG_USER_PASSWORD_CONSISTENT.getErrMsg());
            }
            String newPswd = PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(newPassword);
            entity.setPassword(newPswd);
            UserModel userModel = organizationFacade.updateUser(entity);
            return getOkResponseResult(username, "根据用户账号修改密码成功");
        } else {
            return getErrResponseResult(username, ErrCode.ORG_USER_PASSWORD_INCONSISTENT.getErrCode(), ErrCode.ORG_USER_PASSWORD_INCONSISTENT.getErrMsg());
        }
    }

    public ResponseResult<UserVO> reset(String id) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ErrCode.SYS_PARAMETER_EMPTY.getErrCode(), ErrCode.SYS_PARAMETER_EMPTY.getErrMsg(), "");
        }
        UserModel user = organizationFacade.getUser(id);
        if (user == null) {
            return getErrResponseResult(null, ErrCode.ORG_USER_NONEXISTENT.getErrCode(), ErrCode.ORG_USER_NONEXISTENT.getErrMsg());
        }
        if (Objects.equals(user.getStatus(), UserStatus.DISABLE)) {
            return getErrResponseResult(null, ErrCode.ORG_USER_DISABLE.getErrCode(), ErrCode.ORG_USER_DISABLE.getErrMsg());
        }
        user.setPassword(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123456"));
        organizationFacade.updateUser(user);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return getOkResponseResult(userVO, "重置密码成功");
    }

    public ResponseResult<List<UserManagerVO>> listManagerConfig(String userId) {
        OrganizationFacade organizationFacade = dubboConfigService.getOrganizationFacade();
        UserModel userModel = organizationFacade.getUser(userId);
        if (userModel == null) {
            throw new ServiceException(ErrCode.ORG_USER_NONEXISTENT);
        }
        List<DepartmentUserModel> deptUserList = organizationFacade.getDepartmentUsersByUserId(userId);
        if (CollectionUtils.isEmpty(deptUserList)) {
            throw new ServiceException(ErrCode.ORG_USER_DEPT_EMPTY);
        }
        List<DepartmentModel> departmentList = organizationFacade.getDepartmentsByDeptIds(deptUserList.stream().map(DepartmentUserModel::getDeptId).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(departmentList)) {
            throw new ServiceException(ErrCode.ORG_USER_DEPT_EMPTY);
        }
        Map<String, DepartmentModel> deptMap = departmentList.stream().collect(Collectors.toMap(DepartmentModel::getId, item -> item));
        List<UserManagerVO> result = new ArrayList<>(deptUserList.size());
        List<OrgDirectManagerModel> modelList = organizationFacade.listUserManagerByUserId(userId);
        Map<String, UserModel> managerMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(modelList)) {
            managerMap = organizationFacade.getUsers(modelList.stream().map(OrgDirectManagerModel::getManagerId).collect(Collectors.toList()));
        }
        Map<String, UserModel> finalManagerMap = managerMap;
        deptUserList.forEach(deptUser -> {
            UserManagerVO userManagerVO = new UserManagerVO();
            userManagerVO.setUserId(userId);
            userManagerVO.setUserName(userModel.getName());
            DepartmentModel department = deptMap.get(deptUser.getDeptId());
            UserManagerVO.UserManagerBody userDept = UserManagerVO.UserManagerBody.builder().id(deptUser.getDeptId()).name(department == null ? "" : department.getName()).unitType(UnitType.DEPARTMENT.getIndex()).build();
            userManagerVO.setDept(Collections.singletonList(userDept));
            if (CollectionUtils.isNotEmpty(modelList)) {
                modelList.stream().filter(item -> deptUser.getDeptId().equals(item.getDeptId())).findAny().ifPresent(item -> {
                    UserManagerVO.UserManagerBody managerBody = UserManagerVO.UserManagerBody.builder().id(item.getManagerId()).unitType(UnitType.USER.getIndex()).build();
                    UserModel managerModel = finalManagerMap.get(item.getManagerId());
                    managerBody.setName(managerModel == null ? "" : managerModel.getName());
                    userManagerVO.setManager(managerBody);
                });
            }
            userManagerVO.setIsMainDept(deptUser.getDeptId().equals(userModel.getDepartmentId()));
            result.add(userManagerVO);
        });
        return getOkResponseResult(result, "查询用户直属主管记录成功");
    }
}